<script setup lang="tsx">
import {computed, nextTick, PropType, ref, watch} from 'vue'
import { Descriptions, DescriptionsSchema } from '@/components/Descriptions'
import {ElTag, ElPagination, ElUpload, ElEmpty, ElSpace, UploadFile} from 'element-plus'
import {BaseButton} from "@/components/Button";
import {createImageViewer} from "@/components/ImageViewer";
import {PatientType} from "@/api/patient/types";
import {PictureType} from "@/api/picture/types";
import {getImgPath} from "@/utils/image";
import {PictureClassPatientType} from "@/api/pictureClass/types";
import {propTypes} from "@/utils/propTypes";
import {useEventBus} from "@/hooks/event/useEventBus";
const emits = defineEmits(['onUpload', 'onDelete', 'onSwitchGroup', "onPrint"])
const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<PatientType>>,
    default: () => null
  },
  images: {
    type: Array as PropType<Array<PictureType>>,
    default: () => []
  },
  imgIndex: propTypes.number.def(0),
  currentGroup: {
    type: Object as PropType<Nullable<PictureClassPatientType>>
  },
  height: propTypes.number.def(0),
})

let openPreview = false

const img = ref<string>()
let index = ref(props.imgIndex)
const {emit} = useEventBus()
watch(
    ()=>props.images,
    ()=> {
      img.value = props.images[index.value]?.url || ""
      // 目前正在预览图片
      if (openPreview){
        emit("closePreview")
        nextTick(()=>{
          index.value = props.imgIndex
          previewImg()
        })
      }
    },
    {
      deep: true,
      immediate: true
    }
)
watch(
    ()=>props.imgIndex,
    ()=>{
      index.value = props.imgIndex
      img.value = props.images[index.value].url
    }
)
// const changeImg = (current: number)=>{
//   console.log(current)
//   index.value = current - 1
//   img.value = props.images[index.value].url
// }
const showImg = computed(()=>{
  const path = img.value || ""
  return getImgPath(path)
})
const title = computed(()=>{
  return props.currentGroup?.name || "病历预览"
})
const uploading = ref(false)
const upload = async(file: UploadFile)=>{
  emits("onUpload", file)
}
const showPreview = computed(()=>props.images.length>0)
const previewImg = ()=>{
  // window.open(img.value)
  const arr = props.images.map(item=> getImgPath(item.url))
  openPreview = true
  createImageViewer({
    urlList: arr,
    initialIndex: index.value,
    title: title.value,
    onJump: (type, index)=>{
      // 跳转上/下一组
      emits('onSwitchGroup', {type, current: index})
    },
    onClose: ()=>{
      openPreview = false
    }
  })
}
const print = ()=>{
  emits("onPrint")
}
const schema = computed<DescriptionsSchema[]>(()=>{
  return [
    {
      field: 'action',
      label: '操作',
      span: 24,
      slots: {
        default: () => {
          const openPreview = ()=>{
            index.value = 0
            previewImg()
          }
          const delImg = ()=>{
            const pic = props.images[index.value]
            emits('onDelete', pic)
          }
          return (
              <div>
                <ElSpace>
                  <ElUpload
                      ref="uploadRef"
                      class="upload-demo"
                      auto-upload={false}
                      show-file-list={false}
                      multiple={true}
                      onChange={upload}
                  >
                    <slot name='trigger'>
                      <BaseButton type="primary" loading={uploading.value}>上传图片</BaseButton>
                    </slot>
                  </ElUpload>
                  {
                    showPreview.value ?
                      <ElSpace>
                        <BaseButton type="info" onClick={openPreview}>病历预览</BaseButton>
                        <BaseButton type="success" onClick={print}>病历打印</BaseButton>
                        <BaseButton type='danger' onClick={delImg}>删除该扫描件</BaseButton>
                      </ElSpace> :
                      null
                  }
                </ElSpace>
              </div>
          )
        }
      }
    },
    {
      field: 'content',
      label: '病例扫描件',
      span: 24,
      slots: {
        default: () => {
          const openImg = ()=>{
            previewImg()
          }
          if(props.images?.length){
            return (
                <div class="img-box" style={{height: props.height + 'px'}}>
                  <img src={showImg.value} alt="" onClick={openImg}/>
                </div>
            )
          } else {
            return (
                <ElEmpty description='暂未上传电子扫描件'></ElEmpty>
            )
          }
        }
      }
    }
  ]
})
const openImg = ()=>{
  previewImg()
}
</script>

<template>
  <div>
<!--    <Descriptions :schema="schema" :data="currentRow || {}"/>-->
    <div class="img-box" :style="{height: props.height + 'px'}">
    <img :src="showImg" alt="" @click="openImg"/>
  </div>
  </div>
</template>

<style lang="less">
.img-box{
  width: 100%;
  background-color: #eee;
  flex: 1;
  img{
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
}
</style>